
import { ConnectState } from "../NetConfig"
import IServiceTarget from "./IServiceTarget";
/**
 * 统一长连接和短连接的接口。
 */
export default abstract class BaseService {

    constructor(url: string, port?: number) {
        this.url = url;
        this.port = port;


    }

    //链接状态
    protected state: string = ConnectState.CLOSED;

    protected url: string;

    protected port: number;

    protected target: IServiceTarget;

    setTarget(target: IServiceTarget) {
        this.target = target;
        // this.messageList = [];
    }

    getUrl() {
        return this.url
    }

    getPort() {
        return this.port;
    }



    abstract connect(): void

    /**
     * 服务是否准备好 短连接协议直接返回true。
     */
    isReady() {
        return this.state == ConnectState.OPEN;
    }

    getState() {
        return this.state;
    }

    /**
      * 发送数据调用，子类实现自己的细节。
      * @param message 需要发送的消息
      */
    abstract sendData(message: net.SendMessage): void;

    destroy(): void {
    }
    /**
      * 连接打开 短连接直接调用该函数 统一使用方式。
      * @param data 
      */
    onOpen(data?) {
        this.state = ConnectState.OPEN;
        this.target.onOpen(data)
    }

    onData(data: any) {
        this.target.onData(data)
    }

    onError(data?: any) {
        this.state = ConnectState.ERROR;
        this.target.onError(data)
    }

    onClose(data?) {
        this.state = ConnectState.CLOSED;
        this.target.onClose(data)
    }
}
